<?php
class Project_manager extends Controller {
	function __construct()
	{
		parent::Controller();
		if($this -> session -> userdata('user_id') === FALSE)
			redirect("login/doLogout");
		
		if($this -> session -> userdata('level') < 99)
		{
			$this -> session -> set_flashdata('message', 'You had no rights to page you tried to access.');
			redirect("core");
		}
	}
	
	function index()
	{
		$this -> load -> library('table');
		$this -> load -> model('project_model');
		
		$data['page_title'] = "List of projects";
		$arr = $this -> project_model -> getProjects();
		$tmpl = array(	'table_open' => '<table class="listTable" cellpadding="5" cellspacing="0">',
						'row_start' => '<tr class="even">',
						'row_alt_start' => '<tr class="odd">');
		$this -> table -> set_template($tmpl);
		$this -> table -> set_heading('Project name', 'Status', 'Description', 'Edit');
		foreach($arr as $row)
		{
			$row[] = anchor("project_manager/newProject/{$row['id']}", "Edit");
			unset($row['id']);
			$this -> table -> add_row($row);
		}
		
		$data['project_table'] = $this -> table -> generate();
		
		$this -> load -> view('project_manager', $data);
	}
	
	function newProject()
	{
		$pid = $this -> uri -> segment(3, 0);
		if($pid)
			$data['page_title'] = "Modify the project";
		else
			$data['page_title'] = "Add a new project";
			
		$this -> load -> model('project_model');
		$this -> load -> model('user_model');
		
		$data['users'] = $this -> user_model -> getUsers();
		$data['involved'] = $this -> project_model -> getProjectUsers($pid);
//		print_r($data['involved']);
		if($pid)
		{
			$arr = $this -> project_model -> getProjects($pid);
			$data += $arr[0];
		}
		else
		{
			$arr = array("id" => 0, "name" => "", "status" => "", "description" => ""); // going around stupid thing in CodeIgniter
			$data += $arr;
		}
		
		$this -> load -> view("add_modify_view", $data);
	}
	
	function manageProject()
	{
		$this -> load -> model('project_model');
		
		if($this -> input -> post('name') == false)
		{
			$this -> session -> set_flashdata('message', 'Project had no name. Cannot continue!');
			redirect("project_manager/newProject");
		}
		
		$arr['name']		= $this -> input -> post('name');
		$arr['status']		= $this -> input -> post('status');
		$arr['description']	= $this -> input -> post('description');
		
		$this -> project_model -> manageProject($arr, $this -> input -> post('pid'), $this -> input -> post('user'));
		redirect('project_manager');
	}
	
}